//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.yaukie.base.config;

import java.io.PrintWriter;
import java.io.StringWriter;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaukie.base.constant.BaseResult;
import org.yaukie.base.constant.BaseResultConstant;
import org.yaukie.base.exception.UserDefinedException;

@RestControllerAdvice(
        annotations = {RestController.class}
)
public class UniformReponseHandler<T> {
    private static final Logger log = LoggerFactory.getLogger(UniformReponseHandler.class);

    public UniformReponseHandler() {
    }

    @PostConstruct
    public void setUp() {
        log.debug("统一异常处理机制开启了...");
    }

    @ResponseStatus(HttpStatus.OK)
    public BaseResult sendSuccessResponse() {
        return BaseResult.success();
    }

    @ResponseStatus(HttpStatus.OK)
    public BaseResult sendSuccessResponse(T data) {
        return BaseResult.success(data);
    }

    @ExceptionHandler({UserDefinedException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResult sendErrorResponse_UserDefined(Exception exception) {
        return new BaseResult(((UserDefinedException)exception).getException(), (Object)null);
    }

    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResult sendErrorResponse_System(Exception exception) {
        if (exception instanceof UserDefinedException) {
            return this.sendErrorResponse_UserDefined(exception);
        } else {
            StringWriter sw = new StringWriter();
            exception.printStackTrace(new PrintWriter(sw));
            String msg = sw.toString().substring(0, 800);
            return new BaseResult(BaseResultConstant.FAILED, msg);
        }
    }
}
